﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Transaction
{
    public partial class Form1 : Form
    {
        const string ConStr = "Data Source=.;Initial Catalog=ADO_NET_Simple;Integrated Security=True";
        public Form1()
        {
            InitializeComponent();
        }

        private void btnSubmit_Click(object sender, EventArgs e)
        {
            using (SqlConnection conn=new SqlConnection(ConStr))
            {
                conn.Open();
                //开启事务
                SqlTransaction transaction = conn.BeginTransaction();
                
                try
                {
                    string sql = "update Banks set Money+=1000 where id=3";
                    //用SqlTransaction初始化SqlCommand
                    SqlCommand comm = new SqlCommand(sql, conn,transaction);
                    comm.ExecuteNonQuery();
                    sql = "update Banks set Money-=1000 where id=2";
                    comm.CommandText = sql;
                    comm.ExecuteNonQuery();
                    transaction.Commit();
                    MessageBox.Show("转账成功");
                }
                catch (Exception ex)
                {
                    transaction.Rollback();
                    MessageBox.Show("转账失败\n" + ex.Message);
                }
            }
        }
    }
}
